import { defineStore } from 'pinia'
import { store } from '@/stores'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY, useCache, deleteUserCache } from '@/hooks/web/useCache'
import { getUserInfo, logout } from '@/api/base/login'

const { wsCache } = useCache()

interface UserType {
  userId: string
  avatar: string
  nickname: string
  deptId: number
}

interface UserInfoState {
  user: UserType
  roles: string[]
  permissions: string[]
  isUserSet: boolean
}

/**
 * 存储 用户信息、用户角色、用户授权 的状态
 */
export const useUserStore = defineStore('user', {
  state: (): UserInfoState => {
    return {
      user: {
        // 用户信息
        userId: '',
        nickname: '',
        avatar: '',
        deptId: 0
      },
      roles: [], // 用户角色列表
      permissions: [], // 用户授权列表
      isUserSet: false
    }
  },
  getters: {
    getUser(): UserType {
      return this.user
    },
    getUserId(): string {
      return this.user?.userId
    },
    getRoles(): string[] {
      return this.roles
    },
    getPermissions(): string[] {
      return this.permissions
    },
    getIsUserSet(): boolean {
      return this.isUserSet
    }
  },
  actions: {
    async setUserInfo() {
      if (!getAccessToken()) {
        this.resetState()
        return
      }
      let userInfo = wsCache.get(CACHE_KEY.USER)
      // 刷新页面时，缓存中有用户信息则直接从缓存数据重建state，否则从服务器获取
      if (!userInfo) {
        userInfo = await getUserInfo()
      }
      this.user = userInfo.user
      this.roles = userInfo.roles
      this.permissions = userInfo.permissions
      this.isUserSet = true
      wsCache.set(CACHE_KEY.USER, userInfo)
      wsCache.set(CACHE_KEY.ROLE_ROUTES, userInfo.menus)
    },
    setUserAvatar(avatar: string) {
      this.user.avatar = avatar
      const userInfo = wsCache.get(CACHE_KEY.USER)
      if (userInfo?.user) {
        userInfo.user.avatar = avatar
        wsCache.set(CACHE_KEY.USER, userInfo)
      }
    },
    setUserNickname(nickname: string) {
      this.user.nickname = nickname
      const userInfo = wsCache.get(CACHE_KEY.USER)
      if (userInfo?.user) {
        userInfo.user.nickname = nickname
        wsCache.set(CACHE_KEY.USER, userInfo)
      }
    },
    async logout() {
      await logout().catch(() => {})
      removeToken()
      deleteUserCache()
      this.resetState()
    },
    resetState() {
      this.user = {
        userId: '',
        nickname: '',
        avatar: '',
        deptId: 0
      }
      this.roles = []
      this.permissions = []
      this.isUserSet = false
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
